package handlers

import (
	"github.com/gin-gonic/gin"
	"pet-manager/cache"
	"pet-manager/models"
	"pet-manager/pkg"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不能为空",
		})
		return
	}
	redis_key := "login" + username
	errCount, _ := cache.Rdb.Get(cache.Ctx, redis_key).Int()
	var user models.User
	err := models.DB.Where("username = ?", username).Find(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户查询失败",
		})
		return
	}
	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户不存在",
		})
		return
	}

	if user.Password != pkg.Md5Str(password) {
		cache.Rdb.Incr(cache.Ctx, password)
		if errCount == 2 {
			c.JSON(200, gin.H{
				"code": 500,
				"msg":  "密码错误封禁2小时",
			})
			return
		}
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误封禁2小时",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 500,
		"msg":  "登录成功",
	})
	return
}
